package pers.zb.docker.example.dao;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import pers.zb.docker.example.entity.User;

import java.util.List;

@Component
public class UserDao {

    @Autowired
    private MyJdbcTemplate myJdbcTemplate;
    /**
     * 查询所有用户列表
     */
    public List<User> searchAllUsers(){
        //查询语句SQL
        String sql = "SELECT u.id,u.user_name userName,u.create_time createTime FROM user u";
        return myJdbcTemplate.getTemplate().query(sql, new Object[]{}, new BeanPropertyRowMapper<User>(User.class));
    }





    // ===================================================================================================================================
    // 为了省事，我就直接在类中声明了一个内部类，用于获取JdbcTemplate
    // ===================================================================================================================================

    /**
     * 获取JdbcTemplate
     *
     * 【说明】：这里我就不通过在项目中集成mybatis框架了，为了简单实现这个功能，直接使用JdbcTemplate来访问数据库。
     */
    @Component
    public static class MyJdbcTemplate{
        @Value("#{configProperties['jdbc.driverClassName']}")
        private String driverClassName;

        @Value("#{configProperties['jdbc.url']}")
        private String url;

        @Value("#{configProperties['jdbc.username']}")
        private String username;

        @Value("#{configProperties['jdbc.password']}")
        private String password;

        private BasicDataSource basicDataSource = null;
        private JdbcTemplate jdbcTemplate = null;
        /**
         * 创建数据源并获取JdbcTemplate
         */
        public  JdbcTemplate getTemplate(){
            if(jdbcTemplate != null){
                return jdbcTemplate;
            }
            if(basicDataSource == null){
                basicDataSource = new BasicDataSource();
                basicDataSource.setDriverClassName(driverClassName);
                basicDataSource.setUrl(url);
                basicDataSource.setUsername(username);
                basicDataSource.setPassword(password);
                /*basicDataSource.setInitialSize(50);
                basicDataSource.setMaxActive(100);
                basicDataSource.setMaxIdle(50);
                basicDataSource.setMinIdle(40);
                basicDataSource.setMaxWait(100);*/
            }
            jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(basicDataSource);
            return jdbcTemplate;
        }
    }
}
